﻿using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Xml;
using CID.Execution.Support.PackageRegistration;

namespace CID.Execution.Controller.PackageRegistration
{
    public class WebPackageRegistrationServiceConfigurator : PackageRegistrationServiceConfiguratorBase
    {
        private const string HostingUrlAttribute = "hostingUrl";
        private ServiceHost serviceHost;
        public WebPackageRegistrationServiceConfigurator(XmlElement xml) : base(xml)
        {
        }

        public override void SetUp()
        {
            var hostingUrl = Configuration.GetAttribute(HostingUrlAttribute);
            serviceHost = new ServiceHost(typeof(WebPackageRegistrationService), new Uri(hostingUrl));
            serviceHost.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetEnabled = true });
            serviceHost.Open();
        }

        internal bool IsConfigured
        {
            get { return ((serviceHost != null) && (serviceHost.State == CommunicationState.Opened)); }
        }

        public override void TearDown()
        {
            if(IsConfigured)
            {
                serviceHost.Close();
                serviceHost = null;
            }
        }
    }
}
